package com.amsp.oa.oademo.service.impl;

import com.amsp.oa.oademo.entity.FileReview;
import com.amsp.oa.oademo.entity.ReviewDepartment;
import com.amsp.oa.oademo.mapper.FileReviewMapper;
import com.amsp.oa.oademo.mapper.ReviewDepartmentMapper;
import com.amsp.oa.oademo.service.FileReviewService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class FileReviewServiceImpl extends ServiceImpl<FileReviewMapper, FileReview> implements FileReviewService {

    @Autowired
    private ReviewDepartmentMapper reviewDepartmentMapper;

    @Override
    public IPage<FileReview> getPage(Integer current, Integer size, String keyword) {
        Page<FileReview> page = new Page<>(current, size);
        LambdaQueryWrapper<FileReview> wrapper = new LambdaQueryWrapper<>();

        if (StringUtils.isNotBlank(keyword)) {
            wrapper.like(FileReview::getFileName, keyword)
                    .or()
                    .like(FileReview::getFileNumber, keyword)
                    .or()
                    .like(FileReview::getApplicationDepartment, keyword);
        }

        wrapper.orderByDesc(FileReview::getCreateTime);
        return this.page(page, wrapper);
    }

    @Override
    public FileReview getDetailById(Long id) {
        FileReview fileReview = this.getById(id);
        if (fileReview != null) {
            LambdaQueryWrapper<ReviewDepartment> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ReviewDepartment::getReviewId, id);
            List<ReviewDepartment> departments = reviewDepartmentMapper.selectList(wrapper);
            fileReview.setReviewDepartments(departments);
        }
        return fileReview;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveOrUpdateWithDepartments(FileReview fileReview) {
        boolean result = this.saveOrUpdate(fileReview);
        if (result && fileReview.getReviewDepartments() != null) {
            // 删除原有的部门数据
            LambdaQueryWrapper<ReviewDepartment> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ReviewDepartment::getReviewId, fileReview.getId());
            reviewDepartmentMapper.delete(wrapper);

            // 保存新的部门数据
            for (ReviewDepartment department : fileReview.getReviewDepartments()) {
                department.setReviewId(fileReview.getId());
                reviewDepartmentMapper.insert(department);
            }
        }
        return result;
    }
}